

var uploader = {
    'data':{
        'token':'',
        'uploadDomain':'',
        'domain':''
    },
    'complete':function(res){
        var url="http://"+uploader.data.domain +"/"+ res.key;

        // $(".pic-pic").attr("src",url);
        // $(".hidden-pic").val(url);
        var barimg = '<div class="banner-css">\n' +
            '                        <label onclick="delbanner(this)"' +
            '><img src="'+url+'" class="banner-pic"></label>\n' +
            '                        <input type="hidden" name="list_img[]" value="'+res.key+'" class="hidden-picc">\n' +
            '                    </div>';
        $('.default').val('');
        $('.banner-img').append(barimg);
    },

    'complete2':function(res){
        var url="http://"+uploader.data.domain +"/"+ res.key;
        $(".pic3").attr("src",url);
        $(".hidden-pic3").val(res.key);
    },
    'complete3':function(res){
        var imgval = '.imgindex'+res['x:img'];
        var url="http://"+uploader.data.domain +"/"+ res.key;
        $(imgval).val(res.key)
    },
    'error':function () {
        console.dir(arguments);
    },
    // 分片上传时的进度展示功能在此书写.
    'next':function (response) {
        // var chunks = response.chunks || [];
        // var total = response.total;
    },
    'init':function(){
        $.ajax({
            'url':'/upload/get-token',
            'type':'POST',
            'dataType':'json',
            'success':function(data){
                if(data.code != 200)
                {
                    layer.alert(data.msg);
                    return false;
                }
                uploader.data.token = data.data.token;      // token
                uploader.data.domain = data.data.domain;    // 显示域名
                // uploader.data.uploadDomain = 'idv093d.qiniudns.com';    // 上传域名
                console.log(uploader.data.domain)
            }
        });
    },
    'eventBind':function(){
        this.init();
        $('.default').on('change',function () {
            var token = uploader.data.token;
            var config = {
                useCdnDomain: true,
                disableStatisticsReport: false,
                region: qiniu.region.z0
            };
            var putExtra = {
                fname: "",
                params: {},
                mimeType: ["image/png", "image/jpeg", "image/gif"], // 限制文件类型.
            };
            var file = this.files[0];
            var observable;
            if (file) {
                var files=$(".default")[0].files[0];    // 用来显示的文件名.需要修改,重名时覆盖
                var key1=file.name;
                var key=key1.split(".")[0]+randomNum()+"."+key1.split(".")[1];
                console.log(key)
                putExtra.params["x:name"] = key.split(".")[0];
                // 配置完成的数组.
                var subObject = {
                    next: uploader.next,
                    error: uploader.error,
                    complete: uploader.complete
                };
                var subscription;
                // 调用sdk上传接口获得相应的observable，控制上传和暂停
                observable = qiniu.upload(files, key, token, putExtra, config);
                subscription = observable.subscribe(subObject);
                // subscription.unsubscribe();  // 取消上传.
            }
        });

        $('.pic-card3').on('change',function () {
            var token = uploader.data.token;
            var config = {
                useCdnDomain: true,
                disableStatisticsReport: false,
                region: qiniu.region.z0
            };
            var putExtra = {
                fname: "",
                params: {},
                mimeType: ["image/png", "image/jpeg", "image/gif"], // 限制文件类型.
            };
            var file = this.files[0];
            var observable;
            if (file) {
                var files=$(this)[0].files[0];    // 用来显示的文件名.需要修改,重名时覆盖
                var key1=file.name;
                var key=key1.split(".")[0]+randomNum()+"."+key1.split(".")[1];
                putExtra.params["x:name"] = key.split(".")[0];
                // 配置完成的数组.
                var subObject = {
                    next: uploader.next,
                    error: uploader.error,
                    complete: uploader.complete2
                };
                var subscription;
                // 调用sdk上传接口获得相应的observable，控制上传和暂停
                observable = qiniu.upload(files, key, token, putExtra, config);
                subscription = observable.subscribe(subObject);
                // subscription.unsubscribe();  // 取消上传.
            }
        });
        $('body').on('change','.pic-card4',function () {
            var imgthis = $(this).attr('indexs');

            var token = uploader.data.token;
            var config = {
                useCdnDomain: true,
                disableStatisticsReport: false,
                region: qiniu.region.z0
            };
            var putExtra = {
                fname: "",
                params: {},
                mimeType: ["image/png", "image/jpeg", "image/gif"], // 限制文件类型.
            };
            var file = this.files[0];
            var observable;
            if (file) {
                var files=$(this)[0].files[0];    // 用来显示的文件名.需要修改,重名时覆盖
                var key1=file.name;
                var key=key1.split(".")[0]+randomNum()+"."+key1.split(".")[1];
                putExtra.params["x:name"] = key.split(".")[0];
                putExtra.params["x:img"] = imgthis;
                // 配置完成的数组.
                var subObject = {
                    next: uploader.next,
                    error: uploader.error,
                    complete: uploader.complete3
                };
                var subscription;
                // 调用sdk上传接口获得相应的observable，控制上传和暂停
                observable = qiniu.upload(files, key, token, putExtra, config);
                subscription = observable.subscribe(subObject);
                // subscription.unsubscribe();  // 取消上传.
            }
        });
    }
};

//三级联动
$('.oneclass').change(function () {
    var classid = $(".oneclass option:selected").val();
    $('.twoclass').html('');
    $('.threeclass').html('');
    changeclassAjax('.twoclass',classid,'一')
})

$('.twoclass').change(function () {
    var classid = $(".twoclass option:selected").val();
    $('.threeclass').html('');
    changeclassAjax('.threeclass',classid,'二')
})
function changeclassAjax(calsss,id,num) {
    $.ajax({
        'url': '/googs/get-tree',
        'type': 'POST',
        'dataType': 'json',
        'data': {id:id},
        'success': function (data) {
            if (data.code != 200) {
                layer.alert(data.msg);
                return false;
            } else {
                var option = '<option value="0">请选择'+num+'级分类</option>';
                $.each(data.data,function(indexe,value){
                    option += '<option value="'+value.id+'">'+value.tree_name+'</option>'
                });
                console.log(calsss);
                $(calsss).append(option);
            }
        }
    });
}

function delbanner($this) {
    if(confirm('确定删除当前图片？')){
        $($this).parent().remove();
    }
}

var tool = {toolbars:[
        [
            'undo', //撤销
            'redo', //重做
            'bold', //加粗
            'indent', //首行缩进
            'snapscreen', //截图
            'italic', //斜体
            'underline', //下划线
            'strikethrough', //删除线
            'subscript', //下标
            'fontborder', //字符边框
            'superscript', //上标
            'formatmatch', //格式刷
            'source', //源代码
            'blockquote', //引用
            'pasteplain', //纯文本粘贴模式
            'selectall', //全选
            'print', //打印
            'preview', //预览
            'horizontal', //分隔线
            'removeformat', //清除格式
            'time', //时间
            'date', //日期
            'unlink', //取消链接
            'insertrow', //前插入行
            'insertcol', //前插入列
            'fontfamily', //字体
            'fontsize', //字号
            'paragraph', //段落格式
            'simpleupload', //单图上传
            'edittable', //表格属性
            'justifyleft', //居左对齐
            'justifyright', //居右对齐
            'justifycenter', //居中对齐
            'justifyjustify', //两端对齐
            'forecolor', //字体颜色
            'backcolor', //背景色
            'insertorderedlist', //有序列表
            'insertunorderedlist', //无序列表
            'fullscreen', //全屏
        ]
    ]}



$(document).ready(function(){

    // var ue = UE.getEditor('editor',tool);
    var index = $('.attr-count').val();
    uploader.eventBind();

    //添加规格
    $('.addlist').click(function () {

        var attr = $('.appendinfo tr:last');
        var attr_value = attr.find($("input[name='attr_value']")).val();
        var original_price = attr.find($("input[name='original_price']")).val();
        var discount_price = attr.find($("input[name='discount_price']")).val();
        var inventory = attr.find($("input[name='inventory']")).val()?attr.find($("input[name='inventory']")).val():'';
        var attrimgval = attr.find($("input[name='attrimgval']")).val()?attr.find($("input[name='attrimgval']")).val():'';
        index++;
        var html = '<tr class="addshuxing">';
        html += '<td><input type="text" class="span10 menu-name attr_value attrList" placeholder="规格名" name="attr_value" value="'+attr_value+'"></td>'
        html += '<td><input type="text" class="span10 menu-name original_price attrList"  name="original_price" placeholder="0.00" value="'+original_price+'"></td>'
        html += '<td><input type="text" class="span10 menu-name discount_price attrList" name="discount_price" placeholder="0.00" value="'+discount_price+'"></td>'
        html += '<td><input type="text" class="span10 menu-name inventory attrList" placeholder="0" name="inventory" value="0"></td>';
        html += '<td width="90px;"><input type="file"  class="pic-card4" indexs="'+index+'"><input type="hidden" name="attrimgval" value="" class="attrimgvalue imgindex'+index+' attrList"></td>';
        html += '<td><input onclick="addtabletr(this)" type="button" value="删除"></td>';
        html += '<input type="hidden" class="attr_id attrList" name="attr_id" value="0"></td>';
        html += '</tr>';
            $('.appendinfo').append(html);
    })

    //传递数据
    $(".btn-last-googs").on("click",function(){

        var id = $('.hidden-googs-id').val();
        // $.ajax({
        //     'url': '/googs/getgoodss',
        //     'type': 'POST',
        //     'dataType': 'json',
        //     'data': {id: id},
        //     'success': function (data) {
        //         if (data.code != 200) {
        //             layer.msg('活动进行中的商品不能修改', function(){
        //                 flag = false;
        //                 return;
        //             });
        //         }
        //     }
        // })

        var newattr = [];
        $('.addshuxing').each(function(i){
            var attrarr = [];
            $('.addshuxing').eq(i).find(".attrList").each(function (j) {
                attrarr.push($(this).val())
            })
            newattr.push(attrarr);
        });
        var threeid = $(".threeclass option:selected").val();  //三级分类
        var twoid = $(".twoclass option:selected").val();  //二级分类
        var oneid = $(".oneclass option:selected").val();  //一级分类
        var googs_name = $(":input[name='googs_name']").val();
        var type = $(":input[name='type']").val();
        var key = $(":input[name='key']").val();
        var list_img = $(":input[name='list_img']").val();
        var attr_name = $(":input[name='attr_name']").val();
        var googs_id = $(":input[name='googs_id']").val();
        var freight = $(":input[name='freight']").val();
        var introduction = $("#introduction").val();
        // var content = UE.getEditor('editor').getContent();

        var banner = new Array();
        $('.hidden-picc').each(function($i){
            banner[$i] = $(this).val();
        });

        data = {'googs_name':googs_name,'type':type,'key':key,'list_img':list_img,'introduction':introduction
            ,'attr_name':attr_name,'googs_id':googs_id,'banner':banner
            ,'two_tree_id':twoid,'one_tree_id':oneid,'three_tree_id':threeid,'newattr':newattr,'freight':freight
        };
        flag = true;
        if(threeid == 0){
            layer.msg("请选择三级分类");
            flag = false;
        }else if(googs_name == ""){
            layer.msg("请输入商品名称");
            flag = false;
        }else if(attr_name == ''){
            layer.msg("请填写规格名");
            flag = false;
        }else if(list_img == ''){
            layer.msg("请上传列表图");
            flag = false;
        }else if(banner.length == 0){
            layer.msg("请添加详情图");
            flag = false;
        }
        if(flag) {
            $.ajax({
                'url': '/googs/update-googs',
                'type': 'POST',
                'dataType': 'json',
                'data': data,
                'success': function (data) {
                    if (data.code != 200) {
                        layer.alert(data.msg);
                        return false;
                    } else {
                        layer.msg(data.msg);
                        setTimeout(function(){
                            location.href="/googs/index";
                        },1000);
                    }

                }
            });
        }
    });



})

$('.introductions').on('keydown',function () {
    var indexs = 220;
    var texts = $(this).val().length;
    indexs = indexs-texts;
    if(indexs < 0){
        layer.alert('已超过220个字符');
    }
    $('.testcount').html(indexs);
})

function addtabletr($this) {
    $($this).parent().parent().remove();
}


